/*
 * Copyright 2005-2013 finalist.cn. All rights reserved.
 * Support: http://www.finalist.cn
 * License: http://www.finalist.cn/license
 */
package com.finalist.service.impl;

import java.util.Date;

import javax.annotation.Resource;
import javax.persistence.LockModeType;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.finalist.dao.PaymentDao;
import com.finalist.entity.Member;
import com.finalist.entity.Order;
import com.finalist.entity.Payment;
import com.finalist.entity.Payment.Status;
import com.finalist.entity.Payment.Type;
import com.finalist.service.MemberService;
import com.finalist.service.OrderService;
import com.finalist.service.PaymentService;

/**
 * Service - 收款单
 * 
 * @author Finalist IT Group
 * @version 3.0
 */
@Service("paymentServiceImpl")
public class PaymentServiceImpl extends BaseServiceImpl<Payment, Long> implements PaymentService
{

    private Logger log = Logger.getLogger(PaymentServiceImpl.class);

    @Resource(name = "paymentDaoImpl")
    private PaymentDao paymentDao;
    @Resource(name = "orderServiceImpl")
    private OrderService orderService;
    @Resource(name = "memberServiceImpl")
    private MemberService memberService;

    @Resource(name = "paymentDaoImpl")
    public void setBaseDao(PaymentDao paymentDao)
    {
        super.setBaseDao(paymentDao);
    }

    @Transactional(readOnly = true)
    public Payment findBySn(String sn)
    {
        return paymentDao.findBySn(sn);
    }

    public void handle(Payment payment)
    {

        paymentDao.refresh(payment, LockModeType.PESSIMISTIC_WRITE);
        if (payment != null && payment.getStatus() == Status.wait)
        {
            if (payment.getType() == Type.payment)
            {
                Order order = payment.getOrder();
                if (order != null)
                {
                    orderService.payment(order, payment, null);
                }
            }
            else if (payment.getType() == Type.recharge)
            {
                Member member = payment.getMember();
                if (member != null)
                {
                    memberService.update(member, null, payment.getEffectiveAmount(), null, null);
                }
            }
            else if (payment.getType() == Type.phoneCharge)
            {
            }
            payment.setStatus(Status.success);
            payment.setPaymentDate(new Date());
            paymentDao.merge(payment);

        }
    }

    @Override
    public Payment findByChargeLog(Long chargeLogId)
    {
        return paymentDao.findByChargeLogId(chargeLogId);
    }

	@Override
	public Payment findByOrder(Long orderId) {
		return paymentDao.findByorderId(orderId);
	}

}